package endpoint

import (
	"center/db"
	"common/pb"
	"common/rs"
	"context"
	"go.uber.org/zap"
)

func (s *MetainfoServer) DetailObject(ctx context.Context, req *pb.ObjectDetailRequest) (_ *pb.ObjectDetailResponse, err error) {
	defer func() {
		err = Error.Wrap(err)
		s.log.Info("DetailObjects",
			zap.ByteString("bucket", req.Bucket), zap.Error(err))
	}()
	apiKey, err := s.validateAuth(ctx, req.Header)
	if err != nil {
		return nil, err
	}
	//检查bucket是否存在
	bucket, err := s.db.GetBucketByName(ctx, string(req.Bucket), apiKey.Head())
	if err != nil {
		return nil, err
	}

	object, err := s.db.DetailObject(ctx, bucket.ID, string(req.EncryptedObjectKey))
	if err != nil {
		return nil, err
	}
	return &pb.ObjectDetailResponse{
		StreamId:           object.StreamId.Bytes(),
		Bucket:             bucket.Bucket,
		Rs:                 rs.ToPbRs(object.Redundancy),
		Inline:             object.Inline,
		EncryptedObjectKey: []byte(object.EncryptObjectKey),
		SegmentCount:       int32(object.SegmentCount),
		PlainSize:          object.PlainSize,
		Attributes:         object.Attribute,
	}, nil
}

func (s *MetainfoServer) BatchDetailObject(ctx context.Context, req *pb.BatchObjectDetailRequest) (_ *pb.BatchObjectDetailResponse, err error) {
	defer func() {
		err = Error.Wrap(err)
		s.log.Info("BatchDetailObjects",
			zap.ByteString("bucket", req.Bucket), zap.Error(err))
	}()
	apiKey, err := s.validateAuth(ctx, req.Header)
	if err != nil {
		return nil, err
	}
	//检查bucket是否存在
	bucket, err := s.db.GetBucketByName(ctx, string(req.Bucket), apiKey.Head())
	if err != nil {
		return nil, err
	}

	objects, err := s.db.ListObjects(ctx, db.ListObjects{
		BucketId:         bucket.ID,
		EncryptObjectKey: req.EncryptedObjectKey,
	})

	if err != nil {
		return nil, err
	}
	data := new(pb.BatchObjectDetailResponse)
	data.Items = make([]*pb.ObjectDetailResponse, len(objects))

	for i := range objects {
		data.Items[i] = &pb.ObjectDetailResponse{
			StreamId:           objects[i].StreamId.Bytes(),
			Bucket:             bucket.Bucket,
			Rs:                 rs.ToPbRs(objects[i].Redundancy),
			Inline:             objects[i].Inline,
			EncryptedObjectKey: []byte(objects[i].EncryptObjectKey),
			SegmentCount:       int32(objects[i].SegmentCount),
			PlainSize:          objects[i].PlainSize,
		}
	}
	return data, nil
}
